import type GeoCoordinates from '@/types/generic/GeoCoordinates'
interface Coordinate {
  latitude: number
  longitude: number
}
function toRadians(degrees: number): number {
  return (degrees * Math.PI) / 180
}

function toDegrees(radians: number): number {
  return (radians * 180) / Math.PI
}
export default class GeoCoordinateUtils {
  private static EARTH_RADIUS_KM: number = 6371

  public static getCenterPoint(coordinates: GeoCoordinates[]): Coordinate | null {
    if (coordinates === null || coordinates.length === 0) {
      return null
    }

    let latitude = 0.0
    let longitude = 0.0

    for (const coord of coordinates) {
      latitude += toRadians(coord.latitude!)
      longitude += toRadians(coord.longitude!)
    }

    const numOfPoints = coordinates.length
    return {
      latitude: toDegrees(latitude / numOfPoints),
      longitude: toDegrees(longitude / numOfPoints)
    }
  }

  public static calculateDistance(lon1: number, lat1: number, lon2: number, lat2: number): number {
    const latDistance = toRadians(lat2 - lat1)
    const lonDistance = toRadians(lon2 - lon1)

    const a =
      Math.sin(latDistance / 2) * Math.sin(latDistance / 2) +
      Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2)

    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))

    return this.EARTH_RADIUS_KM * c
  }
}
